package org.example.test.tracing;

import brave.Tracing;
import zipkin2.Span;
import zipkin2.reporter.AsyncReporter;
import zipkin2.reporter.Reporter;
import zipkin2.reporter.okhttp3.OkHttpSender;

public class ZipkinManualDemo {
    Tracing tracing = TracingConfig.getTracing();

    public static void main(String[] args) {
        System.out.println("begin tracing");
        ZipkinManualDemo test = new ZipkinManualDemo();
        test.firstBiz();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void firstBiz() {
        tracing.tracer().startScopedSpan("parentSpan");
        brave.Span span = tracing.tracer().currentSpan();
        span.tag("key", "firstBiz");
        secondBiz();
        span.finish();
    }

    private void secondBiz() {
        tracing.tracer().startScopedSpanWithParent("childSpan", tracing.tracer().currentSpan().context());
        brave.Span childSpan = tracing.tracer().currentSpan();
        childSpan.tag("key", "secondBiz");
        childSpan.finish();
        System.out.println("end tracing, id: " + childSpan.context().traceIdString());
    }

    private static class TracingConfig {
        private static final String zipkinEndpoint = "http://localhost:9411/api/v2/spans";
        private static String localServiceName = "zipkinManualDemo";
        private static Tracing tracing = null;

        static {
            OkHttpSender sender = OkHttpSender.newBuilder().endpoint(zipkinEndpoint).build();
            Reporter<Span> reporter = AsyncReporter.builder(sender).build();
            tracing = Tracing.newBuilder().localServiceName(localServiceName).spanReporter(reporter).build();
        }

        public static Tracing getTracing() { return tracing; }
    }
}
